Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
Is the format specifier %[^\n]s legal in C89?

I'm reading a string from sdin with a scanf by doing:

scanf("%[^\n]s", msg);

%[^\n]s reads till a new line character is found. Is this legal in ANSI-C?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You should not use this format for multiple reasons:

  • The s in "%[^\n]s" is not part of the conversion specifier, it is a plain character that scanf will try to match after the characters read from the line, at a time where the current character is either a newline or the end of file. You should remove the s.

  • scanf("%[^\n]", msg); will fail and return 0, leaving msg unchanged if the user hits enter with an empty input line.

  • scanf("%[^\n]", msg); will cause a buffer overflow for any sufficiently long input line. The maximum number of characters to store into the array pointed to by msg should be specified between the % and the [ as:

      char buf[100];
      if (scanf("%99[^\n]", msg) == 1) {
          // msg contains the input line, up to 99 characters
          // the remainder if this input line is still in stdin
          // so is the newline
      }
    
  • scanf("%99[^\n]", msg); does not consume the newline and leaves extra characters in the input stream if more than 99 were typed before the newline, which may of may not be the expected behavior.

Here is a safer alternative:

// read a line of input, discard extra characters and the trailing newline
int mygets(char *dest, size_t size) {
    int c;
    size_t i = 0;
    while ((c = getchar()) != EOF && c != '\n') {
        if (i + 1 < size) {
            dest[i++] = c;
        }
    }
    if (size > 0)
        dest[i] = '\0';
    if (c == EOF && (i == 0 || ferror(stdin)))
        return EOF;
    else
        return (int)i;
}
over 4 years ago · Santiago Trujillo Relatório

0

Is the format specifier %[^\n]s legal in C89?

Yes, it's "legal", as in the behavior will be defined.

The %[^\n] will scan anything except a newline character. s will scan an s. s will never match, because there will be a newline in the buffer, or an error condition. Still, it's "valid".

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda